import { getQNToken } from '@/api/updata'
import * as qiniu from 'qiniu-js'
import { computeMD5, fileObj2Arr, showUploadProcess } from '@/utils/upload'
import { addApp, setApp } from '@/api/app'
import { notification, message } from 'ant-design-vue'

const upload = {
  state: {
    uploadListApp: {},
  },
  getters: {
    getUploadListApp: state => {
      console.log(state.uploadListApp);
      return state.uploadListApp
    },
  },
  mutations: {
    SET_UPLOAD_LIST_APP (state, list) {
      state.uploadListApp = list
    }
  },
  actions: {
    async pushUploadItemApp ({ commit, state, dispatch }, { formData, success,  }) {
      // 初始化七牛云上传实例
      const { data } = await getQNToken()
      const uploadIconKey = await computeMD5(formData.iconUrl);
      let apkKey = !formData.apk ? formData.md5 : '';
      let iconKey = formData.icon == uploadIconKey ? uploadIconKey : '';
      // 没有修改图标和apk文件
      if(apkKey && iconKey) {
        dispatch('submitData', {
          data: {
            ...formData,
            iconKey,
            apkKey,
          },
          success
        });
        return;
      }
      const sort = Date.now()
      // 新icon文件
      if(!iconKey) {
        const observableIcon = qiniu.upload(formData.iconUrl, uploadIconKey, data.data)
        const subscriptionIcon = observableIcon.subscribe({
          next ({ total }) {
            const { size, loaded } = total
            // 获取上传列表
            const list = state.uploadListApp
            list[uploadIconKey] = {
              ...list[uploadIconKey],
              subscriptionIcon,
              fileName: `icon-${uploadIconKey}.png`,
              sort,
              fileSize: size,
              uploadSize: loaded
            }
            commit('SET_UPLOAD_LIST_APP', list)
            showUploadProcess(fileObj2Arr(state.uploadListApp));
          },
          error (err) {
            console.log("七牛云上传出错，错误信息：", err)
            notification.error({
              message: '错误',
              description: '文件上传失败，请检查网络或文件',
              duration: 0
            })
          },
          async complete ({ key }) {
            // 获取上传列表
            // const list = state.uploadList
            // list[uploadKey].assetsKey = key
            // commit('SET_UPLOAD_LIST', list)
            // const uploadData = list[uploadKey]
            iconKey = key;
            if(iconKey && apkKey) {
              dispatch('submitData', {
                data: {
                  ...formData,
                  iconKey,
                  apkKey,
                },
                success
              });
            }
          }
        })
      }
      // 新apk文件
      if(!apkKey) {
        const uploadKey = await computeMD5(formData.apk.file);
        const observable = qiniu.upload(formData.apk.file, uploadKey, data.data)
        const fileName = formData.apk.file.name
        const subscription = observable.subscribe({
          next ({ total }) {
            const { size, loaded } = total
            // 获取上传列表
            const list = state.uploadListApp
            list[uploadKey] = {
              ...list[uploadKey],
              subscription,
              fileName,
              sort,
              fileSize: size,
              uploadSize: loaded
            }
            commit('SET_UPLOAD_LIST_APP', list)
            showUploadProcess(fileObj2Arr(state.uploadListApp));
          },
          error (err) {
            console.log("七牛云上传出错，错误信息：", err)
            notification.error({
              message: '错误',
              description: '文件上传失败，请检查网络或文件',
              duration: 0
            })
          },
          async complete ({ key }) {
            // 获取上传列表
            apkKey = key;
            if(iconKey && apkKey) {
              dispatch('submitData', {
                data: {
                  ...formData,
                  iconKey,
                  apkKey,
                },
                success
              });
            }
          }
        })
      }
    },
    async submitData(_, {
      data,
      success,
    }) {
      console.log("🚀 ~ file: uploadApp.js:127 ~ submitData ~ data:", data)
      const { iconKey, apkKey } = data;
      const api = data.id ? setApp : addApp;
      const { data: { status, msg } } = await api({
        ...data,
        md5: apkKey,
        url: apkKey,
        icon: iconKey,
      });
      if(status != 200) {
        message.error(msg);
        return;
      }
      typeof success == 'function' && success();
    },
    async awaitSubmit({ commit, state }, { key, data }) {
      const list = state.uploadListApp;
      list[key] = {
        ...list[key],
        ...data,
      };
      commit('SET_UPLOAD_LIST_APP', list)
    },
    cancelUpload({ commit, state }) {
      const list = state.uploadListApp || {};
      for (const key in list) {
        if (Object.hasOwnProperty.call(list, key)) {
          const element = list[key];
          element?.subscription?.unsubscribe();
        }
      }
      commit('SET_UPLOAD_LIST_APP', {});
    }
  }
}

export default upload
